package com.wangjiang.foundation.mybatis.controller;

import com.wangjiang.foundation.common.util.ClassUtil;
import com.wangjiang.foundation.mybatis.entity.BaseEntity;
import com.wangjiang.foundation.mybatis.entity.BaseVO;
import com.wangjiang.foundation.mybatis.service.CurdService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public abstract class AbstractCurdController<E extends BaseEntity, V extends BaseVO<E>>
        implements CurdController<E, V> {

    protected final Class<V> voType;

    @Autowired
    protected CurdService<E, V> service;

    protected AbstractCurdController() {
        this.voType = (Class<V>) ClassUtil.getGenericType(this.getClass(), 1);
    }

    public CurdService<E, V> getService() {
        return service;
    }

    public V createModel() {
        return getService().createVoInstance();
    }

    @Override
    public V entityToModel(E entity) {
        V vo = createModel();
        return vo.convertFrom(entity);
    }

    @Override
    public E modelToEntity(V model) {
        E entity = model.convertTo();
        return entity;
    }

    List<E> modelToEntity(Collection<V> models) {
        return models.stream().map(this::modelToEntity).collect(Collectors.toList());
    }
}
